#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include "Log.hpp"
#include <netinet/in.h>
#include <strings.h>
#include <arpa/inet.h>
#include <string.h>

using namespace LogModule;

class UdpServer
{
public:
    UdpServer(const std::string &ip, uint16_t port)
        : _ip(ip), _port(port), _isrunning(false)
    {
    }
    ~UdpServer()
    {
    }
    void Init()
    {
        // 1、创建socket
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket creat failed!";
        }
        LOG(LogLevel::INFO) << "socket creat success" << _sockfd;

        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = inet_addr(_ip.c_str());

        int n = bind(_sockfd, (sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            return;
        }
        LOG(LogLevel::INFO) << "bind success";
    }

    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            char buffer[1024];
            memset(buffer, 0, sizeof(buffer) - 1);
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "recvfrom failed";
                return;
            }
            buffer[n] = 0;
            std::cout << "Client say# :" << buffer << std::endl;
            int ret = sendto(_sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&peer, sizeof(peer));
            if (ret < 0)
            {
                LOG(LogLevel::ERROR) << "sento failed";
            }
        }
        return;
    }

private:
    int _sockfd;
    std::string _ip;
    uint16_t _port;
    bool _isrunning;
};